//
//  NearSearchViewController.m
//  CarLife
//
//  Created by yu on 2017/11/10.
//  Copyright © 2017年 jpas. All rights reserved.
//

#import "NearSearchViewController.h"
#import "SearchBarView.h"
#import "HistorySearchRecord.h"
#import "NearHandleCell.h"
#import <AMapSearchKit/AMapSearchKit.h>
#import <AMapSearchKit/AMapSearchAPI.h>
#import "SearchLocation.h"
#import "NearResultCell.h"
#import "SearchListViewController.h"
#import "SelectListViewController.h"
#import "SearchAnnotation.h"


@interface NearSearchViewController ()<UITableViewDelegate,UITableViewDataSource,SearchBarDelegate,AMapSearchDelegate>
{
    NSString *_record;
}

@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UITableView *sTableView;

@property (nonatomic, strong) SearchBarView *searchBar;

@property (nonatomic, strong) NSMutableArray *historyList;

@property (nonatomic, strong) NSMutableArray *tips;

@property (nonatomic, strong) HistorySearchRecord *historySearchRecord;

@property (nonatomic, strong) AMapSearchAPI *search;

@property (nonatomic, strong) NSMutableArray *poiAnnotations;

@end

static NSString *kNearHandleCellIdentifier = @"NearHandleCellIdentifier";
static NSString *kNearHistoryCellIdentifier = @"NearHistoryCellIdentifier";
static NSString *kNearResultCellIdentifier = @"NearResultCellIdentifier";

@implementation NearSearchViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setLeftImageNamed:@"back_gray" action:@selector(returnAction)];
    
    if (@available(iOS 13.0, *)) {
        [self setRightItemTitle:@"搜索" titleColor:UIColor.labelColor action:@selector(searchAction)];
    } else {
        [self setRightItemTitle:@"搜索" titleColor:kTextBlackColor action:@selector(searchAction)];
    }
    
    [self setTitleView];
    
    [self.tableView registerNib:NIB_NAMED(@"NearHandleCell") forCellReuseIdentifier:kNearHandleCellIdentifier];
    [self.sTableView registerNib:NIB_NAMED(@"NearResultCell") forCellReuseIdentifier:kNearResultCellIdentifier];
    
    [self initSearch];
}

- (void)setTableView:(UITableView *)tableView
{
    _tableView = tableView;
    if (@available(iOS 13.0, *)) {
        UIColor *bgColor = [UIColor colorWithDynamicProvider:^UIColor * _Nonnull(UITraitCollection * _Nonnull traitCollection) {
            if (traitCollection.userInterfaceStyle == UIUserInterfaceStyleLight) {
                return kBackGroundLightGrayColor;
            } else {
                return UIColor.systemBackgroundColor;
            }
        }];
        _tableView.backgroundColor = bgColor;
    } else {
        _tableView.backgroundColor = kBackGroundLightGrayColor;
    }
}


/* 根据中心点坐标来搜周边的POI. */
- (void)searchPoiWithKeyword:(NSString *)keyword
{
    AMapPOIAroundSearchRequest*request = [[AMapPOIAroundSearchRequest alloc] init];
    
    if (self.locationType == LocationByUserLocation) {
        request.location = [AMapGeoPoint locationWithLatitude:[self.user.latitude floatValue] longitude:[self.user.longitude floatValue]];
    } else {
        request.location = [AMapGeoPoint locationWithLatitude:self.selectPoint.latitude longitude:self.selectPoint.longitude];
        PPLog(@"%lf/%lf",self.selectPoint.latitude,self.selectPoint.longitude);
    }
    
    request.keywords = keyword;
    request.radius   = 2000;
    request.sortrule = 0;
    
    [MBProgressHUD showHUDAddedTo:KEY_WINDOW animated:YES];
    [self.search AMapPOIAroundSearch:request];
}

#pragma mark - Search Delegate

- (void)AMapSearchRequest:(id)request didFailWithError:(NSError *)error
{
    PPLog(@"SearchError:{%@}", error.localizedDescription);
}

- (void)onPOISearchDone:(AMapPOISearchBaseRequest *)request response:(AMapPOISearchResponse *)response
{
    [MBProgressHUD hideHUDForView:KEY_WINDOW];
    [self.searchBar resignFirstResponder];
    //PPLog(@"parking count == %ld",response.pois.count);
    if (response.pois.count == 0)
    {
        [MBProgressHUD showToast:@"未获取到相关内容"];
        return;
    }
    
    [self.mapView removeAnnotations:self.poiAnnotations];
    [self.poiAnnotations removeAllObjects];
    
    [response.pois enumerateObjectsUsingBlock:^(AMapPOI *obj, NSUInteger idx, BOOL *stop) {
        
        SearchAnnotation *annotation = [[SearchAnnotation alloc] init];
        [annotation setCoordinate:CLLocationCoordinate2DMake(obj.location.latitude, obj.location.longitude)];
        
        [annotation setTitle:obj.name];
        [annotation setSubtitle:obj.address];
        [annotation setName:obj.name];
        [annotation setAddress:obj.address];
        [annotation setDistance:obj.distance];
        [annotation setParkingType:obj.parkingType];
        PPLog(@"name == %@ | distance = %ld | %lf",obj.name,obj.distance,obj.location.latitude);
        [self.poiAnnotations addObject:annotation];
    }];
    
    if (self.poiAnnotations.count == 1) {
        SelectListViewController *select = [[SelectListViewController alloc] init];
        select.selectAnnotation = self.poiAnnotations.firstObject;
        [self.navigationController pushViewController:select animated:YES];
    } else {
        SearchListViewController *list = [[SearchListViewController alloc] init];
        list.naviItemTitle = _record;
        list.annotations = self.poiAnnotations;
        [self.navigationController pushViewController:list animated:YES];
    }
}

- (void)initSearch
{
    self.search = [[AMapSearchAPI alloc] init];
    self.search.delegate = self;
}

- (void)setTitleView
{
    if (self.searchBar == nil) {
        self.searchBar = [[SearchBarView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth*0.68, 30)];
        self.searchBar.s_delegate = self;
        
        NSString *title = [self.selectAnnotation title];
//        PPLog(@"title1 = %@",title);
        if (!title) {
            title = @"搜索 我的位置 周边";
        } else {
            if (title.length > 7) {
                title = NSStringFormat(@"搜索 %@... 周边",[title substringWithRange:NSMakeRange(0,7)]);
                PPLog(@"title2 = %@",title);
            } else {
                title = NSStringFormat(@"搜索 %@ 周边",title);
            }
        }
        
        self.searchBar.placeholder = title;
        [self.navigationItem setTitleView:self.searchBar];
        
        @weakify(self);
        [self.searchBar setHistoryRecordBlock:^(NSString *record) {
            @strongify(self);
            _record = record;
            /* 输入提示搜索 */
            [self searchTipsWithKeyword:record];
        }];
    }
}

#pragma mark -SearchBarDelegate
- (void)searchBarDidBeginEditing:(SearchBarView *)searchBar
{
//    [self.shadowView setHidden:NO];
}

#pragma mark -搜索
- (void)searchAction
{
    if (_record == nil || _record.length == 0)
    {
        [MBProgressHUD showToast:@"请输入关键字"];
        return;
    }

    [self.historySearchRecord saveSearchRecord:_record];
    [self reloadHistoryListData];
    [self.tableView reloadData];
    
    [self searchPoiWithKeyword:_record];
}

#pragma mark - AMapSearch

- (void)onInputTipsSearchDone:(AMapInputTipsSearchRequest *)request response:(AMapInputTipsSearchResponse *)response
{
    self.tips = [[NSMutableArray alloc] init];
    for (AMapTip *tip in response.tips) {
        SearchLocation *loc = [SearchLocation locationWithTip:tip city:request.city];
        if (loc) {
            [self.tips addObject:loc];
        }
    }
    
    if (self.tips.count > 0) {
        [self.sTableView setHidden:NO];
    } else {
        [self.sTableView setHidden:YES];
    }
    [self.sTableView reloadData];
}

#pragma mark - Utility

/* 输入提示 搜索.*/
- (void)searchTipsWithKeyword:(NSString *)keyword
{
//    if (keyword.length == 0)
//    {
//        return;
//    }
    AMapInputTipsSearchRequest *request = [[AMapInputTipsSearchRequest alloc] init];
    
    request.keywords = keyword;
    request.city = self.user.city;
    request.cityLimit = YES;
    
    if (self.locationType == LocationByUserLocation) {
        NSString *location;
        if (!(self.user.longitude && self.user.latitude)) {
            location = NSStringFormat(@"%lf,%lf",116.5845,36.3750);
        } else {
            location = NSStringFormat(@"%@,%@",self.user.longitude, self.user.latitude);
        }
        request.location = location;
    } else {
        request.location = NSStringFormat(@"%lf,%lf",self.selectPoint.longitude,self.selectPoint.latitude);
    }

    [self.search AMapInputTipsSearch:request];
}

#pragma mark -UITableViewDelegate,UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return tableView == self.tableView ? 2:1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (tableView == self.tableView) {
       return section == 0 ? 1 : self.historyList.count;
    } else {
        return self.tips.count;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (tableView == self.tableView) {
        return indexPath.section == 0 ? 146 : 50;
    } else {
        return 65;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (tableView == self.tableView) {
        if (indexPath.section == 0) {
            NearHandleCell *cell = [tableView dequeueReusableCellWithIdentifier:kNearHandleCellIdentifier];
            [cell setHandleActionBlock:^(NSInteger index, NSString *keyword) {
                _record = keyword;
                [self searchPoiWithKeyword:keyword];
            }];
            return cell;
        } else {
            UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kNearHistoryCellIdentifier];
            if (cell == nil) {
                cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:kNearHistoryCellIdentifier];
            }
            
            if (@available(iOS 13.0, *)) {
                cell.contentView.backgroundColor = UIColor.secondarySystemGroupedBackgroundColor;
                cell.textLabel.textColor = UIColor.labelColor;
            } else {
                cell.contentView.backgroundColor = UIColor.whiteColor;
                cell.textLabel.textColor = kTextBlackColor;
            }
            cell.textLabel.font = SYSTEM_FONT(14);
            cell.textLabel.text = self.historyList[indexPath.row];
            return cell;
        }
    } else {
        NearResultCell *cell = [tableView dequeueReusableCellWithIdentifier:kNearResultCellIdentifier];
        SearchLocation *loc = self.tips[indexPath.row];
        [cell updateAttributedTextWithTip:loc keyword:_record];
        return cell;
    }
}

-(void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section {
    if (tableView == self.tableView) {
        if (section == 1) {
            UITableViewHeaderFooterView *header = (UITableViewHeaderFooterView *)view;
            header.contentView.backgroundColor = self.tableView.backgroundColor;
            header.textLabel.font = SYSTEM_FONT(13);
            header.textLabel.textAlignment = NSTextAlignmentCenter;
            if (@available(iOS 13.0, *)) {
                header.textLabel.textColor = UIColor.secondaryLabelColor;
            } else {
                header.textLabel.textColor = kTextLightGrayColor;
            }
            
            if (self.historyList.count == 0) {
                header.textLabel.text = @"暂无搜索记录";
            } else {
                header.textLabel.text = @"";
            }
        }
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (tableView == self.tableView) {
        if (section == 0) {
            return 0;
        } else {
            if (self.historyList.count == 0) {
                return 40;
            } else {
                return 10;
            }
        }
    } else {
        return 0;
    }
}

#pragma mark -footer view

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    if (tableView == self.tableView) {
        if (section == 0) {
            return [UIView new];
        } else {
            if (self.historyList.count != 0) {
                UIButton *clearBtn = [[UIButton alloc] init];
                clearBtn.sd_layout.spaceToSuperView(UIEdgeInsetsZero);
                if (@available(iOS 13.0, *)) {
                    clearBtn.backgroundColor = UIColor.secondarySystemGroupedBackgroundColor;
                    [clearBtn setTitleColor:UIColor.secondaryLabelColor forState:UIControlStateNormal];
                } else {
                    clearBtn.backgroundColor = UIColor.whiteColor;
                    [clearBtn setTitleColor:kTextGrayColor forState:UIControlStateNormal];
                }
                clearBtn.titleLabel.font = SYSTEM_FONT(14);
                [clearBtn setTitle:@"清除历史搜索记录" forState:UIControlStateNormal];
                
                [clearBtn addTarget:self action:@selector(clearHistoryAction) forControlEvents:UIControlEventTouchUpInside];
                return clearBtn;
            } else {
                return [UIView new];
            }
        }
    } else {
        return [UIView new];
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    if (tableView == self.tableView) {
        return section == 0 ? 0 : 45;
    } else {
        return 0;
    }
}

- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (tableView == self.tableView) {
        return @"删除";
    }
    return nil;
}

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (tableView == self.tableView) {
        return UITableViewCellEditingStyleDelete;
    } else {
        return UITableViewCellEditingStyleNone;
    }
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    if (tableView == self.tableView) {
        return indexPath.section == 0 ? NO : YES;
    } else {
        return NO;
    }
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    [self.historySearchRecord deleteHistoryRecord:indexPath.row];
    [self reloadHistoryListData];
    [self.tableView reloadData];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if (tableView == self.tableView) {
        
        if (indexPath.section) {
            NSString *keyword = self.historyList[indexPath.row];
//            PPLog(@"keyword == %@",keyword)
            _record = keyword;
            [self searchPoiWithKeyword:keyword];
        }
    } else {
        SearchLocation *loc = self.tips[indexPath.row];
//        PPLog(@"search location address = %@",loc.name);
//        PPLog(@"%lf",loc.coordinate.latitude);
        
        NSMutableArray *annotations = [NSMutableArray array];
        
        SearchAnnotation *selectAnnotation = [[SearchAnnotation alloc] init];
        selectAnnotation.title = loc.name;
        selectAnnotation.address = loc.address;
        selectAnnotation.district = loc.district;
        selectAnnotation.coordinate = loc.coordinate;
        
        [annotations addObject:selectAnnotation];
        
        SelectListViewController *list = [[SelectListViewController alloc] init];
        list.selectAnnotation = selectAnnotation;
        list.annotations = annotations;
        [self.navigationController pushViewController:list animated:YES];
    }
}

- (void)clearHistoryAction
{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"您确定删除所有搜索记录吗？" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
    }];
    UIAlertAction *certainAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        [self.historySearchRecord deleteAllHistoryRecord];
        [self reloadHistoryListData];
        [self.tableView reloadData];
    }];
    [alert addAction:cancelAction];
    [alert addAction:certainAction];
    [self presentViewController:alert animated:YES completion:nil];
}

- (void)reloadHistoryListData {
    self.historyList = [self.historySearchRecord getHistoryRecord];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self setWhiteNavigationBar];
    self.historyList = [self.historySearchRecord getHistoryRecord];
    
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self setDefaultNavigationBar];
}

- (void)returnAction {
    if (self.searchBar.text.length != 0) {
        self.searchBar.text = @"";
        [self.sTableView setHidden:YES];
    } else {
        [self.searchBar resignFirstResponder];
        [self.navigationController popViewControllerAnimated:YES];
    }
}

- (HistorySearchRecord *)historySearchRecord {
    if (_historySearchRecord == nil) {
        _historySearchRecord = [[HistorySearchRecord alloc] init];
    }
    return _historySearchRecord;
}

- (NSMutableArray *)poiAnnotations {
    if (_poiAnnotations == nil) {
        _poiAnnotations = [NSMutableArray array];
    }
    return _poiAnnotations;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
